package com.stx.threeGrup.interceptor;

import com.stx.threeGrup.model.automodel.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * Created by Administrator on 2019/6/11
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 进入handler方法之前执行
     * 用于身份认证、身份授权
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return true 放行
     * false 拦截不向下执行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //获取请求的URL
//        String url = httpServletRequest.getRequestURI();
        //判断是否是公开地址(一般写在配置当中)
/*        if (url.indexOf("login.do") >= 0) {
            return true;
        }*/
        //判断session
        HttpSession session = httpServletRequest.getSession();
        Enumeration<String> attrs = session.getAttributeNames();
        while(attrs.hasMoreElements()){
// 获取session键值
            String name = attrs.nextElement().toString();
            // 根据键值取session中的值
            Object vakue = session.getAttribute(name);
            // 打印结果
            System.out.println("------" + name + ":" + vakue +"--------\n");
        }
        //从session中取用户信息
        User user= (User) session.getAttribute("user");
//        System.out.println(user.getUserUname());
        if(user!=null){
            return true ;
        }
        return false;
    }

    /**
     * 进入handler方法之后，返回modelAndView之前执行
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
